<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户-->
      <el-col :span="8">
        <div>
          <el-form :inline="true" @submit.native.prevent>
            <el-form-item>
              <el-input
                v-model="searchForm.name"
                type="primary"
                placeholder="请输入名称"
                clearable
                @keyup.enter.native="onSearch"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="onSearch"/>
            </el-form-item>
          </el-form>
          <el-table ref="userTable" :data="userList" border highlight-current-row @current-change="checkUser">
            <el-table-column align="center" fixed prop="date" label="序号">
              <template slot-scope="scope">
                <span>{{ (page.currentPage-1 )* page.pageSize + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="用户名">
              <template slot-scope="scope">
                <span>{{ scope.row.username }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="province" label="真实姓名">
              <template slot-scope="scope">
                <span>{{ scope.row.realName }}</span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="page.currentPage"
            :page-size="page.pageSize"
            :total="page.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
      </el-col>
      <!--账户-->
      <el-col :span="16">
        <div class="title">
          <span>
            <h1>分配给【 {{ currentUser.realName }} 】的账户</h1>
          </span>
        </div>
        <div>
          <el-button type="primary" @click="showDialog">分配账户</el-button>
        </div>
        <div>
          <el-table :data="accounts">
            <el-table-column
              type="index"
              label="序号"/>
            <el-table-column
              prop="accountType.name"
              label="类型"/>
            <el-table-column
              prop="name"
              label="名称"/>
            <el-table-column
              prop="url"
              label="路径"/>
            <el-table-column
              prop="account"
              label="账号"/>
            <el-table-column
              prop="password"
              label="密码"/>
            <el-table-column
              prop="remark"
              label="备注"/>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <!--分配账户的弹窗-->
    <el-dialog :visible.sync="dialogVisible" title="分配账户">
      <template v-for="(accountByType) in assign.allAccountByType">
        <!-- eslint-disable-next-line -->
        <div style="margin: 20px">
          <el-checkbox
            :indeterminate="assign.isCheckSome[accountByType.id]"
            v-model="assign.isCheckAll[accountByType.id]"
            @change="handleCheckAllChange(accountByType.id)">
            {{ accountByType.name }}
          </el-checkbox>
          <div style="margin: 5px 20px;">
            <el-checkbox-group
              v-model="assign.checkedAccounts[accountByType.id]"
              @change="handleCheckedCitiesChange(accountByType.id)">
              <el-checkbox v-for="city in accountByType.accounts" :label="city.id" :key="city.id" style="margin: 8px 15px;">{{ city.name }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </template>
      <div>
        <el-button type="primary" @click="submitAssign">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { UserPageFunc } from '../../api/user';
import { getSysAccountByUserId, getAllByType, assignAccount } from '../../api/password/assignAccount';

export default {
  name: 'Assign',
  data() {
    return {
      dialogVisible: false,
      userList: [],
      // 当前选中的用户
      currentUser: {},
      searchForm: {
        name: ''
      },
      // 分页数据
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      accounts: [], // 用户已分配的账户
      assign: {
        allAccountByType: [], // 分类的账户
        checkedAccounts: {}, // 已选中的
        isCheckSome: {}, // 全选框的状态。选了一部分又没有选完全部的
        isCheckAll: {} // 全选
      }
    };
  },
  created() {
    this.getUser();
  },
  methods: {
    // 搜索
    onSearch() {
      this.page.currentPage = 1;
      this.getUser();
    },
    // 跳转页面
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getUser();
    },
    // 跳转页面
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.getUser();
    },
    // 点击选中用户
    checkUser(user) {
      this.currentUser = user;
      this.getAccount(user.id);
    },
    // 设置被选中的用户
    setCurrent(user) {
      if (user) {
        this.$refs.userTable.setCurrentRow(user);
        this.getAccount(user.id);
      }
    },
    showDialog() {
      this.assign.checkedAccounts = {};
      this.assign.isCheckAll = {};
      this.assign.isCheckSome = {};
      this.dialogVisible = true;
      getAllByType().then(response => {
        this.assign.allAccountByType = response.data;
        this.assign.allAccountByType.map(t => {
          this.$set(this.assign.checkedAccounts, t.id, []);
          this.$set(this.assign.isCheckAll, t.id, false);
          this.$set(this.assign.isCheckSome, t.id, false);
        });
        this.accounts.map(account => {
          this.assign.checkedAccounts[account.accountTypeId].push(account.id);
          this.handleCheckedCitiesChange(account.accountTypeId);
        });
      });
    },
    getUser() {
      let name = this.searchForm.name;
      name = name === '' ? null : name;
      UserPageFunc(this.page.currentPage, this.page.pageSize, name).then(response => {
        this.userList = response.data.rows;
        this.page.total = response.data.total;

        // 默认选中第一个用户
        if (this.userList.length > 0) {
          this.setCurrent(this.userList[0]);
        }
      });
    },
    getAccount(userId) {
      this.accounts = [];
      getSysAccountByUserId(userId).then(response => {
        this.accounts = response.data;
      });
    },
    // 弹出框
    // 全选
    handleCheckAllChange(typeId) {
      const checkAll = this.assign.isCheckAll[typeId];
      this.assign.checkedAccounts[typeId] = checkAll ? this.getAccountIdsByType(typeId) : [];
      this.assign.isCheckSome[typeId] = false;
    },
    getAccountIdsByType(typeId) {
      let accountByType = {};
      this.assign.allAccountByType.map(type => {
        if (type.id === typeId) {
          accountByType = type;
        }
      });
      const ids = [];
      accountByType.accounts.map(account => {
        ids.push(account.id);
      });
      return ids;
    },
    // 选一个
    handleCheckedCitiesChange(typeId) {
      // 已选的
      const checkedCount = this.assign.checkedAccounts[typeId].length;
      // 全部备选的
      const allCount = this.getAccountIdsByType(typeId).length;
      // 备选的跟已选的同样多
      this.assign.isCheckAll[typeId] = allCount === checkedCount;
      this.assign.isCheckSome[typeId] = checkedCount > 0 && checkedCount < allCount;
    },
    // 提交分配账户
    submitAssign() {
      let ids = [];
      for (const typeId in this.assign.checkedAccounts) {
        ids = ids.concat(this.assign.checkedAccounts[typeId]);
      }
      this.dialogVisible = false;
      assignAccount(this.currentUser.id, ids).then(response => {
        this.getAccount(this.currentUser.id);
      });
    }
  }
};
</script>

<style scoped>
  .title {
    text-align: center;
  }
</style>
